<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="query.query.orderNo" clearable placeholder="请输入订单编号" />
      <el-input v-model="query.query.supplierName" clearable placeholder="请输入供应商名称" />
      <el-date-picker v-model="q_p_formDate1" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="daterange"
        range-separator="-" start-placeholder="申请开始日期" end-placeholder="申请结束日期" @change="q_p_selectTimecreate" />
      <el-button type="primary" icon="el-icon-search" @click="search">
        {{ $t("table.search") }}
      </el-button>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">
        生成对账单
      </el-button>
      <el-button type="primary" icon="el-icon-download" @click="handleExport">
        导出
      </el-button>
    </div>
    <el-table :data="tableData" row-key="id" highlight-current-row border
      :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" :selectable="selectableStatus" />
      <el-table-column prop="statementCode" label="对账单单号" />
      <el-table-column prop="invoiceCode" label="发票号" />
      <el-table-column prop="inoutStoreNo" label="申请单号" />
      <el-table-column label="订单编号" prop="businessNo" />
      <el-table-column label="物料名称" prop="materialName" />
      <el-table-column label="物料编码" prop="materialNo" />
      <el-table-column prop="applyType" label="入库类型" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ getRkApplyType(row.applyType) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="inoutStoreNum" label="入库数量" align="center" width="80" />
      <el-table-column label="入库位置" prop="fromWarehouseName" />
      <el-table-column label="供应商名称" prop="partnerName" />
      <el-table-column prop="inoutStoreState" label="入库状态" align="center" width="80">
        <template slot-scope="{ row: { inoutStoreState,inOut } }">
          {{ getInout(inOut, inoutStoreState) }}
          <!-- {{ inOut == 1 && inoutStoreState == 0 ? "待入库" : "已入库" }} -->
        </template>
      </el-table-column>
      <el-table-column label="是否开票" prop="statementCode">
        <template slot-scope="{row:{statementCode}}">
          {{ statementCode ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="订单日期" prop="orderDate">
        <template slot-scope="{ row }">
          <span>{{
            row.orderDate | parseTime("{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入库申请时间" prop="applyTime">
        <template slot-scope="{ row }">
          <span>{{
            row.applyTime | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="确认入库时间" prop="replyTime">
        <template slot-scope="{ row }">
          <span>{{
            row.replyTime | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column :label="$t('table.actions')" align="center" width="120">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleAdd(row)" :disabled="row.statementCode">
            生成对账单
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <pagination v-show="total" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize"
      @pagination="getInfo" />
  </div>
</template>
<script>
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import {
  pageInstoreList,
  accBillingScmOrder,
  accBindBuyStatement,
  wmsStoreApplyBuyStatementList,
  accDetail1Export
} from "@/api/qmsQualityManagement";
import { sysInvoiceHeaderAll } from '@/api/invoice'
import { downfile } from "@/utils";

export default {
  name: "Project",
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      applyTypeList: [{
        label: '调拨入库',
        value: '4'
      }, {
        label: '其他入库',
        value: '6'
      }],
      q_p_formDate1: [],
      query: {
        pageIndex: 1,
        pageSize: 20,
        query: {
          inOut: 1,
          startDate: null,
          endDate: null,
          inStoreState: "1"
        }
      },
      total: 0,
      tableData: [],
      userList: [],
      selectedList: []
    };
  },
  computed: {},
  mounted() {
    this.getday()
    this.getInfo()
    this.getUserPage()
  },
  methods: {
    async handleExport() {
      try {
        let params = { ...this.query }
        params.pageSize = 100000
        await accDetail1Export(params)
      } catch (err) {
        const reader = new FileReader();
        reader.readAsText(err);
        reader.onload = (event) => {
          const resultString = reader.result; // 这里就是转换后的字符串
          if (resultString.includes('code') && resultString.includes('isSuccess')) {
            this.$message.error(JSON.parse(resultString).message)
          } else {
            downfile('入库对账单明细.xlsx', err);
          }
        }
      }
    },
    getInout(inOut, inoutStoreState) {
      if (inOut == 1) {
        return inoutStoreState == 1 ? '已入库' : '待入库'
      } else {
        return inoutStoreState == 1 ? '已出库' : '待出库'
      }
    },
    selectableStatus(row) {
      return !row.statementCode
    },
    handleSelectionChange(e) {
      this.selectedList = [];
      e.forEach(item => {
        this.selectedList.push(item.id);
      });
    },
    async getUserPage() {
      this.userList = await sysInvoiceHeaderAll(this.headerQuery)
    },
    handleAdd() {
      if (!this.selectedList.length) {
        this.$message.warning("请至少选择一条订单");
        return;
      }
      this.$confirm('此操作将生成对账单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await accBindBuyStatement({
          wmsStoreApplyIds: this.selectedList.join(',')
        })
        this.getInfo()
        this.$message.success('操作成功！')
      })
    },
    getRkApplyType(val) {
      if (val == 1) {
        return "销售出库";
      } else if (val == 2) {
        return "采购入库";
      } else if (val == 4) {
        return "调拨入库";
      } else if (val == 5) {
        return "调拨出库";
      } else if (val == 6) {
        return "其他入库";
      } else if (val == 7) {
        return "其他出库"
      } else if (val == 8) {
        return "销售退货入库";
      } else if (val == 9) {
        return "采购退货出库";
      }
    },
    getday() {
      const currDate = new Date().toLocaleDateString()// 2020/11/6
      const arrs = currDate.split('/')
      const arrs1 = arrs.join('-')
      const yy = parseInt(arrs[0]);
      const mm = parseInt(arrs[1]);
      const dd = parseInt(arrs[2]);
      const pdStr = new Date(yy, mm - 1, 1).toLocaleDateString().split('/').join('-');
      this.query.query.startDate = pdStr
      this.query.query.endDate = arrs1
      this.q_p_formDate1 = [pdStr, arrs1]
    },
    q_p_selectTimecreate(val) {
      const { query } = this.query
      if (val) {
        query.startDate = val[0]
        query.endDate = val[1]
      } else {
        query.startDate = query.endDate = ''
      }
    },
    handleSizeChange(size) {
      this.query.pageSize = size;
      this.getInfo();
    },
    handleCurrentChange(currentPage) {
      this.query.pageIndex = currentPage;
      this.getInfo();
    },
    search() {
      this.query.pageIndex = 1;
      this.getInfo();
    },
    getInfo() {
      wmsStoreApplyBuyStatementList(this.query).then(res => {
        const { records, total } = res;
        this.tableData = records;
        this.total = total;
      });
    }
  }
};
</script>

<style scoped>
.addinput /deep/ .el-input__inner {
  border: none;
  background: #f5f7fa;
}

.addinput /deep/ .el-textarea__inner {
  border: none;
  background: #f5f7fa;
}

.downfile {
  text-decoration: underline;
  color: blue;
}
</style>